var PermissionUtil = {
  getPermissionList: function () {
    return SysUtil.getUser().then(function (user) {
      var permissionList = user.permissionList;
      permissionList = _.map(permissionList, function (permission) {
        if (permission.startsWith('/')) {
          return permission.substring(1);
        }
        return permission;
      });
      return permissionList;
    });
  },
  validateAuthority: function (authority) {
    return this.getPermissionList().then(function (permissionList) {
      if (typeof authority === 'string') {
        return permissionList.indexOf(authority) !== -1;
      } else if (_.isArray(authority)) {
        var authorityList = {};
        for (var i = 0; i < authority.length; i++) {
          var permission = authority[i];
          authorityList[permission] = permissionList.indexOf(permission) !== -1;
        }
        return authorityList;
      }
      return null;
    });
  },
  validateAuthorityByUser: function (user, authority) {
    var permissionList = user.permissionList;
    var len = permissionList.length;
    for (var i = 0; i < len; i++) {
      var permission = permissionList[i];
      if (permission.startsWith('/')) {
        permission = permission.substring(1);
      }
      if (permission === authority) {
        return true;
      }
    }
    return false;
  },
  validatePageAuthority: function (page) {
    return SysUtil.getUser().then(function (user) {
      var pageList = user.pageList;
      if (page.indexOf('/') !== 0) {
        page = '/' + page;
      }
      return pageList.indexOf(page) !== 0;
    });
  },
  validatePageAuthorityList:function(pageList){
    return SysUtil.getUser().then(function (user) {
      var pageObj = {};
      var authorityPageList = user.pageList;
      for (var i = 0; i < pageList.length; i++) {
        var page = pageList[i];
        if (page.indexOf('/') !== 0) {
          page = '/' + page;
        }
        pageObj[pageList[i]] = authorityPageList.indexOf(page) !== 0;
      }
      return pageObj;
    });
  },
  ajaxCheckPermission: function (type) {
    return ajaxRequest('approval/checkSelfApprovalPermission', {
      type: type
    }).then(function (hasApproval) {
      return hasApproval;
    });
  }
};